import { Commit } from 'vuex';
import { UserState, UserCorp, UserInfo, Account, PackageInfo, AccountInfo } from './type';
import storage from '@/utils/storage';
import { logOff, getUserInfo } from '@/api/login';
import { getUserGlobalMenu } from '@/api/common';

// 请使用类型定义！！！！
const state: UserState = {
    userInfo: null,
    packageInfo: null,
    corps: <Array<UserCorp>>[],
    currentCorp: null,
    accounts: null,
    accountInfo: null,
    accountStatus: null, // 账户状态码，目前会在接口406的情况下，在登录页面做弹窗展示
    userMenuList: [],
    apiList: <Array<string>>[]
};

const mutations = {
    setUserInfo: (state: UserState, setUser: UserState): void => {
        state.userInfo = setUser.userInfo;
        state.packageInfo = setUser.packageInfo;
        state.corps = setUser.corps;
        state.currentCorp = setUser.currentCorp;
    },
    setFirmInfo: (state: any, setFirm: { userInfo: UserInfo | null }) => {
        state.firmInfo = setFirm;
    },
    setUserToken: (state: any, token: string): void => {
        if (state.userInfo) {
            state.userInfo.loginToken = token;
        } else {
            state.userInfo = {
                id: 0,
                phone: '',
                loginToken: token
            };
        }
    },
    setAccounts: (state: any, accounts: Array<Account>): void => {
        state.accounts = accounts;
    },
    setAccountInfo(state: any, accounts: AccountInfo) {
        state.accountInfo = accounts;
        sessionStorage.setItem('account_info', JSON.stringify(accounts));
    },
    setAccountStatus: (state: any, status: number): void => {
        state.accountStatus = status;
    },
    setUserMenuList: (state: any, userMenuList: any[]): void => {
        state.userMenuList = userMenuList;
    },
    clearUser: (state: any): void => {
        state.userInfo = null;
        state.packageInfo = null;
        state.corps = [];
        state.currentCorp = null;
        state.accounts = null;
        state.accountInfo = null;
        state.accountStatus = null;
        state.userMenuList = [];
    },
    setApiList: (state: any, apiList: any[]): void => {
        state.apiList = apiList;
    }
};

const actions = {
    login: (context: { commit: Commit; state: UserState }, data: any): void => {
        storage.remove('add_customer_select');
        storage.remove('add_customer_optional');
        storage.remove('zw-scrm-state');
        const userInfo: UserInfo = {
            id: data.user_info.id,
            phone: data.user_info.phone,
            loginToken: data.login_token
        };
        const packageInfo: PackageInfo = {
            startTime: data.package_info.start_time,
            expireTime: data.package_info.expire_time,
            packageName: data.package_info.package_name
        };
        const userState: UserState = {
            accounts: [],
            userInfo: userInfo,
            packageInfo: packageInfo,
            corps: data.tenant_corp_list,
            currentCorp: data.current_tenant_corp
        };
        context.commit('setUserInfo', userState);
    },
    loginMultiAccount: (
        context: { commit: Commit; state: UserState },
        playLoad: { login_token: string; account_list: Array<Account> }
    ): void => {
        context.commit('setUserToken', playLoad.login_token);
        context.commit('setAccounts', playLoad.account_list);
    },
    logout: (context: { commit: Commit; state: UserState }) => {
        return new Promise((resolve, reject) => {
            logOff()
                .then(() => {
                    storage.remove('power-code');
                    storage.remove('zw-scrm-state');
                    storage.remove('add_customer_select');
                    storage.remove('add_customer_optional');
                    sessionStorage.clear();
                    localStorage.clear();
                    resolve('');
                })
                .catch((err: Error) => reject(err));
        });
    },
    getUserGlobalMenuFn: (context: { commit: Commit; state: UserState }) => {
        return new Promise((resolve, reject) => {
            getUserGlobalMenu({})
                .then((res: any) => {
                    context.commit('setUserMenuList', res);
                    resolve('');
                })
                .catch((err: Error) => reject(err));
        });
    },
    getAccountInfo: (context: { commit: Commit; state: UserState }) => {
        const params = { ['uth-token']: state.userInfo?.loginToken };
        return new Promise((resolve, reject) => {
            getUserInfo(params)
                .then((res: any) => {
                    context.commit('setAccountInfo', res);
                    localStorage.setItem('owner', res.owner.phone);
                    localStorage.setItem('account_type', res.base_info.account_type);
                    resolve('');
                })
                .catch((err: Error) => reject(err));
        });
    }
};
const getters = {
    getUser: (state: UserState): UserState => state,
    getToken: (state: UserState): string => {
        if (state.userInfo) {
            return state.userInfo.loginToken as string;
        } else {
            return '';
        }
    },
    getCurrentCorp: (state: UserState): number => {
        if (state.currentCorp) {
            return state.currentCorp;
        } else {
            return 0;
        }
    },
    getCurrentCorpName: (state: UserState): string => {
        if (state.currentCorp && state.corps.length) {
            return state.corps.find(item => item.id == state.currentCorp)?.name || '';
        } else {
            return '';
        }
    },
    getAccountInfo: (state: UserState): any => {
        // if(sessionStorage.getItem('account_info')){
        //   return JSON.parse(sessionStorage.getItem('account_info') as string)
        // }else if (state.accountInfo) {
        //   return state.accountInfo
        // }else{
        //   return null
        // }
        if (state.accountInfo) {
            return state.accountInfo;
        } else {
            return null;
        }
    },
    getAccountStatus: (state: UserState): any => {
        return state.accountStatus ?? null;
    },
    getUserMenuList: (state: UserState): any => {
        return state.userMenuList ?? [];
    },
    getApiList: (state: UserState): any => {
        return state.apiList ?? [];
    }
};

const User = {
    namespaced: true,
    state,
    getters,
    mutations,
    actions
};
export default User;
